import { FileUtil } from "@ohos/hvigor";
import * as fs from "fs";
import path from "path";

export default class FileUtils extends FileUtil {
  static contentNotNull(filePath: string) {
    return fs.existsSync(filePath) && fs.statSync(filePath).size > 0;
  }

  static walkSync(
    dir: string,
    regex?: RegExp,
    fileList: string[] = []
  ): string[] {
    const files = fs.readdirSync(dir);

    files.forEach((file) => {
      const filePath = path.join(dir, file);
      const stat = fs.statSync(filePath);

      if (stat.isDirectory()) {
        FileUtils.walkSync(filePath, regex, fileList);
      } else {
        if (FileUtils.contentNotNull(filePath)) {
          if (regex) {
            if (regex.test(filePath)) {
              fileList.push(filePath);
            }
          } else {
            fileList.push(filePath);
          }
        }
      }
    });

    return fileList;
  }

  static mkDir(dirPath) {
    if (!fs.existsSync(dirPath)) {
      fs.mkdirSync(dirPath, { recursive: true });
    }
  }

  static getFileName(filePath): string {
    return path.basename(filePath, path.extname(filePath));
  }

  static deleteDir(dirPath, recursive = true) {
    try {
      if (!fs.existsSync(dirPath)) {
        return;
      }

      if (this.isFile(dirPath)) {
        fs.unlinkSync(dirPath);
        return;
      }

      if (recursive) {
        const files = fs.readdirSync(dirPath);
        for (const file of files) {
          const filePath = path.join(dirPath, file);
          const stats = fs.statSync(filePath);
          if (stats.isDirectory()) {
            FileUtils.deleteDir(filePath, true); // 递归删除子目录
          } else {
            fs.unlinkSync(filePath); // 删除文件
          }
        }
        fs.rmdirSync(dirPath); // 删除空目录
      } else {
        const files = fs.readdirSync(dirPath);
        for (const file of files) {
          const filePath = path.join(dirPath, file);
          const stats = fs.statSync(filePath);
          if (stats.isFile()) {
            fs.unlinkSync(filePath); // 删除文件
          }
        }
      }
    } catch (err) {
      console.error(`Error while deleting ${dirPath}:`, err);
    }
  }
}
